package com.falling.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.falling.reggie.dto.DishDto;
import com.falling.reggie.entity.Dish;
import com.falling.reggie.entity.DishFlavor;
import com.falling.reggie.mapper.DishMapper;
import com.falling.reggie.service.DishFlavorService;
import com.falling.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service("dishService")
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish>
        implements DishService {
    @Resource
    private DishFlavorService dishFlavorService;

    @Override
    @Transactional
    public boolean saveWithFlavor(DishDto dishDto) {
        // 新增菜品同时保存对应口味数据
        if (!super.save(dishDto)) return false;

        Long dishId = dishDto.getId();
        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dishId);
        }

        return dishFlavorService.saveBatch(flavors);
    }


    @Override
    public DishDto getByIdWithFlavor(Long id) {
        Dish dish = super.getById(id);

        // 根据dishID查dish_flavor表，获取对应的flavors
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId, dish.getId());
        List<DishFlavor> flavorList = dishFlavorService.list(queryWrapper);

        // 赋值
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish, dishDto);
        dishDto.setFlavors(flavorList);

        return dishDto;
    }


    @Override
    @Transactional
    public boolean updateWithFlavor(DishDto dishDto) {

        // 更新dish表的基本信息
        super.updateById(dishDto);

        // 先清楚当前dish对应的flavor数据
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId, dishDto.getId());
        dishFlavorService.remove(queryWrapper);

        // 再添加修改的flavor数据
        List<DishFlavor> flavors = dishDto.getFlavors();
        // flavor中需要有dishId，使用stream进行遍历赋值
        flavors = flavors.stream().peek((item) ->
                item.setDishId(dishDto.getId())
        ).collect(Collectors.toList());
        return dishFlavorService.saveBatch(flavors);
    }
}
